package com.insigma.business.common.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.kevinsawicki.http.HttpRequest;
import com.insigma.business.common.service.WechatService;
import com.insigma.business.qrcode.common.dto.ErrorCodeEnum;
import com.insigma.business.qrcode.common.util.BizException;
import com.insigma.business.qrcode.common.util.RedisUtils;
import com.insigma.framework.ResponseMessage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class WechatServiceImpl implements WechatService {
    public static final String accessTokenCacheKey = "wx:accessToken";
    @Value("${wx.url.getAccessToken}")
    private String getAccessTokenUrl;

    @Value("${wx.url.getOpenid}")
    private String getOpenidUrl;

    @Value("${wx.url.getPhoneNumber}")
    private String getPhoneNumberUrl;

    @Value("${wx.url.jscode2session}")
    private String jscode2session;

    @Value("${wx.small.appId}")
    private String appId;

    @Value("${wx.small.appSecret}")
    private String appSecret;

    @Resource
    private RedisUtils redisUtils;

    @Override
    public String getAccessToken() {
        Object accessTokenCache = redisUtils.get(accessTokenCacheKey);
        if (ObjectUtil.isNull(accessTokenCache)) {
            String bodyData = String.format("grant_type=client_credential&appid=%s&secret=%s",appId,appSecret);
            String res = HttpRequest.get(getAccessTokenUrl)
                    .send(bodyData)
                    .body();
            JSONObject jsRes = JSONObject.parseObject(res);
            checkWxResponse(jsRes);
            String accessToken = jsRes.getString("access_token");
            long expiresIn = jsRes.getLong("expires_in");
            redisUtils.set(accessTokenCacheKey,accessToken,expiresIn-300);
            return accessToken;
        } else {
            return (String) accessTokenCache;
        }
    }

    @Override
    public JSONObject jscode2session(String js_code) {
        String bodyData = String.format("appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",appId,appSecret,js_code);
        String res = HttpRequest.get(jscode2session)
                .send(bodyData)
                .body();
        JSONObject jsRes = JSONObject.parseObject(res);
        checkWxResponse(jsRes);
        return jsRes;
    }

    @Override
    public JSONObject getPhoneNumber(String code) {
        JSONObject js = new JSONObject();
        js.put("code",code);
        String url = String.format(getPhoneNumberUrl+"?access_token=%s",getAccessToken());
        String res = HttpRequest.post(url)
                .header("Content-Type", "application/json")
                .send(js.toJSONString())
                .body();
        JSONObject jsRes = JSONObject.parseObject(res);
        checkWxResponse(jsRes);
        return jsRes;
    }

    private void checkWxResponse(JSONObject res) {
        if (res.getInteger("errcode") != null && res.getInteger("errcode") != 0) {
            throw new BizException(ErrorCodeEnum.COMMON_INNER_ERROR,res.getString("errmsg"));
        }
    }

    public static void main(String[] args) {
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber";

    }
}
